#!/usr/bin/env python
#coding=utf-8
import re
import urlparse
import urllib2
import time
from datetime import datetime
import robotparser
import Queue


def link_crawler(seed_url, link_regex=None, delay=5, max_depth=-1, max_urls=-1, 
	headers=None, user_agent='wswp', proxy=None, num_retries=1, scrape_callback=None):
    """爬虫将会爬取相关的链接 使用 link_regex 的规则
    """
    # 队列中的元素要去爬
    crawl_queue = [seed_url]
    # map 表 要爬取的队列爬的次数
    seen = {seed_url: 0}
    # 跟踪有多少个元素已经被爬取
    num_urls = 0
    rp = get_robots(seed_url)
    throttle = Throttle(delay)
    headers = headers or {}
    if user_agent:
        headers['User-agent'] = user_agent

    while crawl_queue:
        url = crawl_queue.pop()
        depth = seen[url]
        # 如果这个代理网页能够爬取
        if rp.can_fetch(user_agent, url):
            throttle.wait(url)
            html = download(url, headers, proxy=proxy, num_retries=num_retries)
            #print "html",html
            links = []
            if scrape_callback:# 如果有回调函数
                links.extend(scrape_callback(url, html) or [])

            if depth != max_depth:
                # can still crawl further
                print 'link_regex', link_regex
                if link_regex:
                    # filter for links matching our regular expression
                    # for link in get_links(html):
	                   #  if re.search(link_regex, link):
	                   #  	print 'search', link
                    links.extend(link for link in get_links(html) if re.search(link_regex, link))

                for link in links:
                    link = normalize(seed_url, link)
                    # check whether already crawled this link
                    if link not in seen:
                        seen[link] = depth + 1
                        # check link is within same domain
                        if same_domain(seed_url, link):
                            # success! add this new link to queue
                            crawl_queue.append(link)

            # check whether have reached downloaded maximum
            num_urls += 1
            if num_urls == max_urls:
                break
        else:
            print 'Blocked by robots.txt:', url


class Throttle:
    """延迟函数
    """
    def __init__(self, delay):
        # 两次间隔的时间
        self.delay = delay
        # timestamp of when a domain was last accessed
        self.domains = {}
        
    def wait(self, url):
        """Delay if have accessed this domain recently
        """
        domain = urlparse.urlsplit(url).netloc # 的到url的主站
        last_accessed = self.domains.get(domain) # 上次爬取的时间  
        if self.delay > 0 and last_accessed is not None:
            sleep_secs = self.delay - (datetime.now() - last_accessed).seconds
            if sleep_secs > 0:
                time.sleep(sleep_secs)
        self.domains[domain] = datetime.now()



def download(url, headers, proxy=False, num_retries=2, data=None):
    print 'Downloading:', url
    request = urllib2.Request(url, data, headers)
    opener = urllib2.build_opener()
    if proxy:
        proxy_params = {urlparse.urlparse(url).scheme: proxy}
        opener.add_handler(urllib2.ProxyHandler(proxy_params))
    try:
        response = opener.open(request)
        html = response.read()
        code = response.code
    except urllib2.URLError as e:
        print 'Download error:', e.reason
        html = ''
        if hasattr(e, 'code'):
            code = e.code
            if num_retries > 0 and 500 <= code < 600:
                # retry 5XX HTTP errors
                html = download(url, headers, proxy, num_retries-1, data)
        else:
            code = None
    return html


def normalize(seed_url, link):
    """ 
    	Normalize this URL by removing hash and adding domain
	    url='http://www.example.com/index.html#print'
		url=urlparse.defrag(url)
		那么返回的url是http://www.example.com/index.html，因为这两个页面实际是同一个url，在爬虫程序中可以用来过滤同一个页面
		url='http://ip/
　　　　 path='api/user/login'
　　　　 urljoin(url,path)拼接后的路径为'http//ip/api/user/login' 路径拼接
    """
    link, _ = urlparse.urldefrag(link) # remove hash to avoid duplicates
    return urlparse.urljoin(seed_url, link)


def same_domain(url1, url2):
    """是否在相同的主站上
    """
    return urlparse.urlparse(url1).netloc == urlparse.urlparse(url2).netloc


def get_robots(url):
    """初始化  robots 解析
    """
    rp = robotparser.RobotFileParser()
    rp.set_url(urlparse.urljoin(url, '/robots.txt'))
    rp.read()
    return rp
        

def get_links(html):
    """返回一个html的所有链接
    """
    # a regular expression to extract all links from the webpage
    webpage_regex = re.compile('<a[^>]+href=["\'](.*?)["\']', re.IGNORECASE)
    # list of all links from the webpage
    #print webpage_regex.findall(html)
    return webpage_regex.findall(html)


if __name__ == '__main__':
    link_crawler('http://example.webscraping.com/places/default', '/(index|view)', delay=0, num_retries=1, user_agent='BadCrawler')
    link_crawler('http://example.webscraping.com/places/default', '/(index|view)', delay=0, num_retries=1, max_depth=1, user_agent='GoodCrawler')
